package com.fly.demo.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.validation.Valid;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fly.common.PaginationSupport;
import com.fly.demo.entity.Customer;
import com.fly.demo.service.CustomerService;
import com.fly.demo.service.impl.CustomerServiceImpl;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * CustomerController
 * 
 * @author 00fly
 * @version [版本号, 2018-09-26]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Slf4j
@Controller
@RequestMapping("/customer")
public class CustomerController
{
    private CustomerService customerService = CustomerServiceImpl.getInstance();
    
    /**
     * String 日期转换为 Date
     * 
     * @param dataBinder
     * @see [类、类#方法、类#成员]
     */
    @InitBinder
    public void dataBinder(WebDataBinder dataBinder)
    {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(df, true));
    }
    
    /**
     * 新增/更新数据
     * 
     * @param customer
     * @return
     * @see [类、类#方法、类#成员]
     */
    @PostMapping("/add")
    public String add(@Valid @ModelAttribute("item") Customer customer, Errors errors, Model model)
    {
        if (errors.hasErrors())
        {
            StringBuilder errorMsg = new StringBuilder();
            for (ObjectError error : errors.getAllErrors())
            {
                errorMsg.append(error.getDefaultMessage()).append(" ");
            }
            if (errorMsg.length() > 0)
            {
                log.info("errors message={}", errorMsg);
            }
            model.addAttribute("page", customerService.queryForPagination(null, 1, 10));
            return "/customer/show";
        }
        // 随机抛出异常
        if (RandomUtils.nextInt() < 100)
        {
            log.info("统一异常处理测试：{}", 12 / 0);
        }
        customerService.saveOrUpdate(customer);
        return "redirect:/customer/list";
    }
    
    /**
     * 删除数据
     * 
     * @param id
     * @return
     * @see [类、类#方法、类#成员]
     */
    @GetMapping("/delete/{id}")
    public String delete(@PathVariable Integer id)
    {
        customerService.deleteById(id);
        return "redirect:/customer/list";
    }
    
    /**
     * 列表展示
     * 
     * @param model
     * @return
     * @see [类、类#方法、类#成员]
     */
    @GetMapping({"/", "/list"})
    public String list(@RequestParam(defaultValue = "1") int pageNo, Model model)
    {
        Customer customer = new Customer();
        if (RandomUtils.nextInt(1, 10) > 1)
        {
            customer.setCustomerName("customer" + RandomStringUtils.randomNumeric(3));
        }
        if (RandomUtils.nextInt(1, 10) > 1)
        {
            customer.setEmail(RandomStringUtils.randomAlphabetic(8) + "@xxx.com");
        }
        PaginationSupport<Customer> page = customerService.queryForPagination(null, pageNo, 10);
        model.addAttribute("item", customer);
        model.addAttribute("page", page);
        return "/customer/show";
    }
    
    /**
     * 编辑数据
     * 
     * @param id
     * @param model
     * @return
     * @see [类、类#方法、类#成员]
     */
    @GetMapping("/update/{id}")
    public String update(@PathVariable Integer id, Model model)
    {
        model.addAttribute("item", customerService.queryById(id));
        model.addAttribute("page", customerService.queryForPagination(null, 1, 10));
        return "/customer/show";
    }
    
    @ResponseBody
    @GetMapping("/all")
    public List<Customer> all()
    {
        return customerService.queryAll();
    }
    
    @ResponseBody
    @GetMapping("/query")
    public Customer query(@RequestBody Customer customer)
    {
        return customer;
    }
}
